import React, { useContext, useState, useMemo } from "react";
import getConfig from "next/config";
import slugify from "slugify";
import { withAuthServerSideProps } from "../../utils/withAuth";
import SEO from "../../components/SEO";
import Text from "../../components/Text";
import TorrentList from "../../components/TorrentList";
import LocaleContext from "../../utils/LocaleContext";
import Box from "../../components/Box";
import styled from "styled-components";

// 轮播图组件
const CarouselWrapper = styled(Box)`
  width: 100%;
  margin: 0 auto 32px auto;
  position: relative;
  overflow: hidden;
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.18);
`;
const CarouselImage = styled.img`
  width: 100%;
  height: 340px;
  object-fit: cover;
  transition: opacity 0.5s;
`;
const CarouselNav = styled(Box)`
  position: absolute;
  bottom: 18px;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  gap: 8px;
`;
const CarouselDot = styled.button`
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: none;
  background: ${({ active, theme }) =>
    active ? theme.colors.primary : "#fff"};
  opacity: ${({ active }) => (active ? 1 : 0.5)};
  cursor: pointer;
`;

const CarouselArrow = styled.button`
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background: rgba(0, 0, 0, 0.18);
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  color: #fff;
  font-size: 22px;
  cursor: pointer;
  z-index: 3;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.2s;
  &:hover {
    background: rgba(0, 0, 0, 0.32);
  }
`;

const CategoryButton = styled.button`
  display: flex;
  align-items: center;
  justify-content: center;
  background: none;
  border: none;
  margin: 0 16px 0 0;
  padding: 8px 20px;
  cursor: pointer;
  outline: none;
  min-width: 90px;
  border-radius: 8px;
  font-size: 18px;
  font-weight: ${({ active }) => (active ? 700 : 500)};
  color: ${({ active, theme }) =>
    active ? theme.colors.primary : theme.colors.text};
  background-color: ${({ active, theme }) =>
    active ? theme.colors.sidebar : "transparent"};
  box-shadow: ${({ active }) =>
    active ? "0 2px 8px rgba(0,0,0,0.08)" : "none"};
  transition: all 0.2s;
  &:hover {
    color: ${({ theme }) => theme.colors.primary};
    background: ${({ theme }) => theme.colors.sidebar};
  }
`;

const carouselImages = [
  "/images/bg1.jpg",
  "/images/bg2.jpg",
  "/images/bg3.jpg",
];

const Categories = ({ allCategories, allTorrents, token }) => {
  if (!allCategories || allCategories.length === 0) {
    return <Text color="grey">暂无可用分类</Text>;
  }
  // 轮播图状态（与分类无关）
  const [carouselIndex, setCarouselIndex] = useState(0);
  // 分类按钮状态
  const [currentCategory, setCurrentCategory] = useState(
    allCategories[0]?.slug || ""
  );
  const { getLocaleString } = useContext(LocaleContext);

  // 轮播图自动切换
  React.useEffect(() => {
    const timer = setInterval(() => {
      setCarouselIndex((prev) => (prev + 1) % carouselImages.length);
    }, 4000);
    return () => clearInterval(timer);
  }, []);

  // 轮播图左右切换
  const handlePrev = () => {
    setCarouselIndex(
      (prev) => (prev - 1 + carouselImages.length) % carouselImages.length
    );
  };
  const handleNext = () => {
    setCarouselIndex((prev) => (prev + 1) % carouselImages.length);
  };

  // 当前分类的种子
  const currentTorrents = useMemo(() => {
    return allTorrents.filter(
      (t) => slugify(t.type, { lower: true }) === currentCategory
    );
  }, [allTorrents, currentCategory]);

  return (
    <>
      <SEO title={getLocaleString("navBrowse")} />
      {/* 轮播图（与分类无关） */}
      <CarouselWrapper>
        <CarouselArrow
          style={{ left: 16 }}
          onClick={handlePrev}
          aria-label="上一张"
        >
          &#8592;
        </CarouselArrow>
        <CarouselArrow
          style={{ right: 16 }}
          onClick={handleNext}
          aria-label="下一张"
        >
          &#8594;
        </CarouselArrow>
        {carouselImages.map((img, idx) => (
          <CarouselImage
            key={img + idx}
            src={img}
            alt={`轮播图${idx + 1}`}
            style={{
              position: idx === carouselIndex ? "static" : "absolute",
              opacity: idx === carouselIndex ? 1 : 0,
              zIndex: idx === carouselIndex ? 2 : 1,
            }}
          />
        ))}
        <CarouselNav>
          {carouselImages.map((_, idx) => (
            <CarouselDot
              key={idx}
              active={idx === carouselIndex}
              onClick={() => setCarouselIndex(idx)}
            />
          ))}
        </CarouselNav>
      </CarouselWrapper>
      {/* 分类按钮 */}
      <Box
        display="flex"
        flexWrap="nowrap"
        mb={5}
        style={{ overflowX: "auto" }}
      >
        {allCategories.map((cat, idx) => (
          <CategoryButton
            key={cat.slug}
            active={cat.slug === currentCategory}
            onClick={() => setCurrentCategory(cat.slug)}
          >
            {cat.name}
          </CategoryButton>
        ))}
      </Box>
      {/* 当前分类的种子列表 */}
      {/*
      <Text as="h1" mb={5}>
        {getLocaleString("navBrowse")} {allCategories.find(c => c.slug === currentCategory)?.name || ""}
      </Text>
      */}
      {currentTorrents.length ? (
        <TorrentList
          torrents={currentTorrents}
          categories={{}}
          total={currentTorrents.length}
          token={token}
        />
      ) : (
        <Text color="grey">{getLocaleString("catNoResults")}</Text>
      )}
    </>
  );
};

export const getServerSideProps = withAuthServerSideProps(
  async ({ token, fetchHeaders }) => {
    const {
      publicRuntimeConfig: { SQ_TORRENT_CATEGORIES, SQ_API_URL },
    } = getConfig();
    // 获取所有种子
    const res = await fetch(`${SQ_API_URL}/torrent/search?limit=1000`, {
      headers: fetchHeaders,
    });
    const results = await res.json();
    const allTorrents = results.torrents || [];
    // 整理分类信息
    const allCategories = Object.keys(SQ_TORRENT_CATEGORIES).map((cat) => {
      const slug = slugify(cat, { lower: true });
      return { name: cat, slug };
    });
    return { props: { allCategories, allTorrents, token } };
  },
  true
);

export default Categories;
